import { addSpecTemplate, editSpecTemplate } from "@/services/stock-goods/specTemplateApi";
import { showMsg } from "@/utils/utils";
import { ModalForm, ProFormText } from "@ant-design/pro-form";
import { ActionType, EditableProTable, ProColumns } from "@ant-design/pro-table";
import { Form, FormInstance } from "antd";
import React, { useEffect, useRef, useState } from "react";

const SpecForm = (props: ModalProps) => {

  const { open, onOpenChange, rowData } = props;

  const actionRef = useRef<ActionType>();
  const modalForm = useRef<FormInstance>();
  const [editFormRef] = Form.useForm();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);

  const columns: ProColumns[] = [
    {
      title: '序号',
      width: 80,
      editable: false,
      valueType: 'index'
    },
    {
      title: '规格名称',
      dataIndex: 'name',
      formItemProps: { rules: [{ required: true, message: '名称是必填项' }] }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      render: (text, record, _, action) => [
        <a key="edit" onClick={() => { action?.startEditable?.(record.key); }}>编辑</a>
        ,
        <a key="del" onClick={() => setDataSource(dataSource.filter(r => r.key !== record.key))}>删除</a>
      ]
    }
  ];

  useEffect(() => {
    setDataSource(rowData?.template_conent.map((elem, idx) => ({ key: `o${idx}`, name: elem })) || []);
    modalForm.current?.setFieldsValue({ template_name: rowData?.template_name });
  }, [rowData]);

  const onFinish = async ({ template_name }: any) => {
    if(editableKeys.length > 0){
      showMsg('请先保存规格行数据');
      return;
    }
    if (dataSource.length === 0) {
      showMsg('请至少添加一个规格');
      return;
    }
    const contentList = dataSource.map(({ name }) => name);
    let req: Promise<STOCKGOODSAPI.SpecTemplate>;
    if (rowData) {
      req = editSpecTemplate(rowData.template_id, template_name, contentList);
    } else {
      req = addSpecTemplate(template_name, contentList);
    }
    req.then(res => {
      showMsg(rowData ? '修改成功' : '添加成功', 'success');
      onOpenChange(false);
    }).catch(err => showMsg(err?.data?.errmsg));
  };

  return (
    <ModalForm
      title="新增/编辑规格模板"
      width="40%"
      layout="horizontal"
      formRef={modalForm}
      modalProps={{ okText: "保存", maskClosable: false, destroyOnClose: true }}
      onVisibleChange={onOpenChange}
      visible={open}
      onFinish={onFinish}
    >
      <ProFormText
        name="template_name"
        label="模板名称"
        placeholder="请输入模板名称"
        rules={[{ required: true }]}
        labelCol={{ flex: '0 0 auto' }}
        wrapperCol={{ flex: '1 0 auto' }}
        fieldProps={{ style: { height: 24 } }}
      />
      <EditableProTable
        rowKey="key"
        columns={columns}
        actionRef={actionRef}
        bordered
        maxLength={20}
        cardProps={{ bodyStyle: { padding: 0 } }}
        recordCreatorProps={{ creatorButtonText: '添加一个规格', newRecordType: "dataSource", record: { key: Date.now().toString() } }}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          form: editFormRef,
          type: 'multiple',
          editableKeys,
          onChange: setEditableRowKeys,
          actionRender: ({ key, index }) => {
            const newDS = [...dataSource];
            const newKeys = editableKeys.filter(eKey => eKey !== key);
            return [
              <a key="save" onClick={() => {
                editFormRef.validateFields([[`${key}`, "name"]]).then((values: any) => {
                  newDS[index] = { ...values[key], key: `D${Date.now()}` };
                  setDataSource(newDS);
                  setEditableRowKeys(newKeys);
                }).catch((error: any) => { });
              }}>保存</a>
              ,
              <a key="cancel" onClick={() => {
                setDataSource(dataSource.filter(r => r.key !== key));
                setEditableRowKeys(newKeys);
              }}>取消</a>
            ];
          }
        }}
      />
    </ModalForm>
  );
};

type ModalProps = {
  open: boolean,
  onOpenChange: (open: boolean) => void,
  rowData?: STOCKGOODSAPI.SpecTemplate
}

export default SpecForm;
